﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using NiuX.Extensions;
using NiuX.LightServer.Extensions;

namespace NiuX.LightServer.Models
{
    /// <summary>
    /// 请求
    /// </summary>
    public class Request
    {
        private readonly string _pathPattern;
        public Request(HttpRequest request, string pathPattern)
        {
            HttpRequest = request;
            _pathPattern = pathPattern;
        }

        public HttpRequest HttpRequest { get; }

        private dynamic _params;
        public dynamic Params => _params ??= PathUtil.MatchPathParams(HttpRequest.Path, _pathPattern);

        private dynamic _query;
        public dynamic Query => _query ??= DynamicQuery();

        private dynamic _header;

        public dynamic Header => _header ??= DynamicHeader();

        public Stream BodyStream => HttpRequest.Body;

        private string _bodyContent;
        public string BodyContent
        {
            get
            {
                if (!string.IsNullOrEmpty(_bodyContent))
                {
                    return _bodyContent;
                }

                using var readStream = new StreamReader(BodyStream, Encoding.UTF8);
                return readStream.ReadToEnd();
            }
        }

        public T Body<T>()
        {
            if (string.IsNullOrEmpty(BodyContent))
            {
                return default(T);
            }

            T obj = BodyContent.ToJson<T>();

            return obj;
        }
        private dynamic DynamicHeader()
        {
            if (HttpRequest == null)
            {
                throw new ArgumentNullException();
            }

            var dict = new Dictionary<string, string>();
            foreach (var keyValuePair in HttpRequest.Headers)
            {
                if (!dict.ContainsKey(keyValuePair.Key))
                {
                    dict.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }

            return dict.ToDynamic();
        }

        private dynamic DynamicQuery()
        {
            if (HttpRequest == null)
            {
                throw new ArgumentNullException();
            }
            var dict = new Dictionary<string, string>();
            foreach (var keyValuePair in HttpRequest.Query)
            {
                if (!dict.ContainsKey(keyValuePair.Key))
                {
                    dict.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }

            return dict.ToDynamic();
        }
    }
}